import { NOT_LOGIN_CODE } from './constants.js';
const web_root = 'https://shop.rcglife.com/';
export const img_root = 'http://img.rcglife.com/';
// 首页
// export const GET_PIC_WALL = "api/getPicwall";                       // 轮播图


export default {
    // POST
    request(url, params, cb, onload) {
        let _this = this;
        wx.request({
            url: web_root + url,
            method: 'POST',
            data: params,
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
                let code = res.data.c;

                if (code == 1) {
                    //正常请求
                    cb && cb(res.data.d);
                } else if (code == NOT_LOGIN_CODE) {
                    //未登录
                    _this.login();
                } else {
                    //接口请求错误
                    wx.showModal({
                        showCancel: false,
                        content: res.data.m,
                    })
                }

            }
        })

    },
    fetch(url, params, cb, errorCb) {
        this.request(url, params, cb, errorCb);
    },
    login(cb) {
        let _this = this;
        wx.login({
            success: function (res) {
                if (res.code) {
                    var code = res.code;
                    wx.getUserInfo({
                        withCredentials: true,
                        success: function (res) {
                            var encryptedData = res.encryptedData;//一定要把加密串转成URI编码
                            var iv = res.iv;
                            //请求自己的服务器
                            _this.fetch(LOGIN, { iv: iv, code: code, encryptedData: encryptedData }, (resp) => {
                                wx.setStorageSync('login', resp);
                                wx.setStorageSync('login_time', new Date().getTime());
                                cb && cb();
                            })
                        }
                    })
                }
            }
        })
    },
    checkLogin(cb){
        let _this = this,
            key = wx.getStorageSync('login'),
            login_time = wx.getStorageSync('login_time'),
            second = 0;

        if (login_time) {
            second = parseInt((new Date().getTime() - login_time) / 1000);
            if (second > 21600) {
                _this.login(cb);
                //登录超时 重新登录
            } else {
                return true;
            }
        } else {
            //登录
            _this.login(cb);
        }
    },
    getKey() {
        return wx.getStorageSync('login');
    }
}